package com.hainabo.mgcmall.filter;

import com.hainabo.mgcmall.model.WxUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Slf4j
@Component
public class UserFilter implements Filter {

    RedisTemplate<String,WxUser>  redisTemplate;

    public RedisTemplate getRedisTemplate() {
        return redisTemplate;
    }
    @Qualifier("redisTemplate")
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }


    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;

        // Chrome Safari 等浏览器跨区会首先提交 OPTIONS(跟 get post put )
        System.out.println(((HttpServletRequest) request).getMethod());
        if (((HttpServletRequest) request).getMethod().equals("OPTIONS")) {
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            //这里填写你允许进行跨域的主机ip
//            httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
            //允许的访问方法
            httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH");
            //Access-Control-Max-Age 用于 CORS 相关配置的缓存
//            httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
//            httpServletResponse.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

            chain.doFilter(request, response);
            return;
        }

        //
        if (req.getRequestURI().indexOf("/api/swagger.json") >= 0
                || req.getRequestURI().indexOf("/api/systemUser/login") >= 0
                || req.getRequestURI().indexOf("/api/systemUser/logout") >= 0) {
            // logger.info("白名单地址通过：" + req.getRequestURI());
            chain.doFilter(request, response);
            return;
        }

        // if ("10.211.55.2".equals(req.getRemoteAddr())) {
        // logger.info("白名单 IP 通过"+req.getRemoteAddr()+" "+req.getRequestURI());
        // chain.doFilter(request, response);
        // return;
        // }
        ValueOperations<String,WxUser> redisTemplate_User = redisTemplate.opsForValue();
        String sessionToken = req.getHeader("sessionToken");
        if (sessionToken == null){
            //sessionToken = req.getParameter("sessionToken");
            response.getWriter().println("{\"code\":-1,\"msg\":\"sessionToken is null\"}");
            return;
        }
        try {
            WxUser user = redisTemplate_User.get(sessionToken);
            log.debug("user:{}",user);
            if(user==null){
                response.getWriter().println("{\"code\":-1,\"msg\":\"会话超时，请重新登陆\"}");
                return;
            }
            if(!"1".equals(user.getStatus())){
                response.getWriter().println("{\"code\":-2,\"msg\":\"账户状态异常,请联系客服\"}");
                return;
            }
//            if (user.getLocked()) {
//                response.getWriter().println("{\"code\":-2,\"msg\":\"system has bean locked\"}");
//                LogWebSocketHandler.broadcastLog(req.getRequestURI() + ", return: system has bean locked");
//                // logger.info(user.getUser_code() + " has bean locked" +
//                // req.getRemoteAddr() + " " + req.getRequestURI());
//                return;
//            }


        } catch (Throwable e) {
//            LogWebSocketHandler.broadcastLog(req.getRequestURI() + ", return: session timeout");
            e.printStackTrace();
            response.getWriter().println("{\"code\":-1,\"msg\":\"session timeout\"}");
            return;
        }

        chain.doFilter(request, response);

    }

    public void destroy() {
    }

    public void init(FilterConfig filterConfig) throws ServletException {
        ServletContext context = filterConfig.getServletContext();//这里获取applicationContext
        ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);

        redisTemplate = (RedisTemplate) ctx.getBean( "redisTemplate");
    }
}